package leeon.mobile.BBSBrowser;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import leeon.mobile.BBSBrowser.UIUtil.GroupListener;
import leeon.mobile.BBSBrowser.UIUtil.PatternListener;
import leeon.mobile.BBSBrowser.actions.HttpConfig;
import leeon.mobile.BBSBrowser.models.BoardObject;
import leeon.mobile.BBSBrowser.models.DocObject;
import weibo4andriod.Paging;
import weibo4andriod.RetweetDetails;
import weibo4andriod.Status;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class WeiboSinaActivity extends ListActivity {
	
	private List<Status> list;
	private BoardObject board;
	private List<BoardObject> boardlist;
	private boolean onlyLogin = false;
	
	private Handler handler = new Handler();
	private TextView title;	
	
	private static Weibo weibo;
	private static String user;
	
	private static final String WEIBO_USER_PATTERN = "@[^\\s\\p{Punct}]+";
	private static final String WEIBO_URL_PATTERN = "http://[sinaurl|t].cn/[\\w]+";
	
	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
    	boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    	
		super.onCreate(savedInstanceState);
		
		board = (BoardObject)this.getIntent().getSerializableExtra("board");
		boardlist = (List<BoardObject>)(this.getIntent().getSerializableExtra("boardlist"));
		onlyLogin = this.getIntent().getBooleanExtra("onlyLogin", false);
		
		list = new ArrayList<Status>();
		getListView().setBackgroundColor(Color.WHITE); 
		getListView().setDivider(getResources().getDrawable(R.drawable.weibo_divider));
		setListAdapter(new StatusListAdapter(list));
		scrollAction.addActionWhenScroll(getListView());
		if (weibo == null) {
			loginWeiBo(true);
		} else {
			scrollAction.refresh();
		}
		
		if (customTitleSupported) {
			getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.weibosina_titlebar);
			title = (TextView)findViewById(R.id.sinaTitle);
			if (user != null) title.setText(user);
		}
	}
	
	@Override 
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
		}
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, final int position, long id) {
		if (UserUtil.CURRENT_USER_ID == null) return;
		postFromWeibo(list.get(position));
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, 1, 1, "切换账号").setIcon(android.R.drawable.ic_menu_myplaces);
		menu.add(0, 2, 2, "刷新微博").setIcon(android.R.drawable.ic_menu_rotate);
        return result;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			loginWeiBo(false);
			break;
		case 2:
			scrollAction.refresh();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void listWeibo(final int totalItemCount) {
		UIUtil.runActionInThread(this, new UIUtil.ActionInThread<Status>() {
			@Override
			public void action() throws NetworkException, ContentException {
				if (weibo != null) {
					try {
						if (list.size() == 0)
							bglist = weibo.getFriendsTimeline();
						else
							bglist = weibo.getFriendsTimeline(
								new Paging().maxId(list.get(totalItemCount-1).getId()-1).count(20));
					} catch (WeiboException ex) {
						throw new NetworkException(ex);
					}
				}
			}
			@Override
			public void actionFinish() {
				if (bglist != null) {
					list.addAll(bglist);
					((BaseAdapter)WeiboSinaActivity.this.getListView().getAdapter()).notifyDataSetChanged();
				}
			}
			
			@Override
			public void actionError() {
				scrollAction.rollback();
			}
		});
	}
	
	private void loginWeiBo(final boolean autoLogin) {
		View view = LayoutInflater.from(this).inflate(R.layout.weibo_login_dialog, null);
		final EditText et1 = (EditText)view.findViewById(R.id.wbUser);
		final EditText et3 = (EditText)view.findViewById(R.id.wbPassword);
		final CheckBox cm = (CheckBox)view.findViewById(R.id.wbRecordPassword);
		
		String p = UserUtil.getWeiBoPassword(this);
		et1.setText(UserUtil.getWeiBoUser(this));
		et3.setText(p);
		
		if (autoLogin && SettingActivity.autoLoginWeibo(this)) {
			if (p != null && p.length() != 0) {
				login(et1.getText().toString(), et3.getText().toString(), cm.isChecked());
				return;
			}
		}

		new AlertDialog.Builder(this)
			.setTitle("登录微博")
			.setView(view)
			.setCancelable(false)
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {					
				public void onClick(DialogInterface dialog, int which) {
					login(et1.getText().toString(), et3.getText().toString(), cm.isChecked());
				}
			})
			.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					if (autoLogin) WeiboSinaActivity.this.finish();
				}
		}).create().show();
	}
	
	
	private void login(final String userId, final String passWord, final boolean saveIt) {
		UIUtil.runActionInThread(this, new UIUtil.ActionInThread<Status>() {
			private Weibo w = new Weibo();
			@Override
			public void action() throws NetworkException, ContentException {
				try {
					w.getXAuthAccessToken(userId, passWord, "client_auth");
				} catch (WeiboException ex) {
					throw new NetworkException(ex);
				}
			}
			@Override
			public void actionFinish() {
				if (saveIt) UserUtil.saveWeiBoUserInfo(WeiboSinaActivity.this, userId, passWord);
				weibo = w;
				if (onlyLogin) 
					WeiboSinaActivity.this.finish();
				else
					scrollAction.refresh();
				user = userId;
				title.setText(userId);
			}
			@Override
			public void actionError() {
				weibo = null;
				if (onlyLogin) 
					WeiboSinaActivity.this.finish();
				else {
					scrollAction.actionClear();
					((BaseAdapter)WeiboSinaActivity.this.getListView().getAdapter()).notifyDataSetChanged();
				}
				user = null;
				title.setText("没有登录");
				
			}
		});
	}
	
	public static Weibo getWeiboInstance(Context context) {
		if (weibo == null) {
			context.startActivity(new Intent(context, WeiboSinaActivity.class).putExtra("onlyLogin", true));
		}
		return weibo;
	}
	
	private void postFromWeibo(final Status s) {
		View view = LayoutInflater.from(this).inflate(R.layout.weibo_re_dialog, null);		
		final EditText et1 = (EditText)view.findViewById(R.id.wbTitle);
		final CheckBox cm1 = (CheckBox)view.findViewById(R.id.wbPostRetweet);
		final CheckBox cm2 = (CheckBox)view.findViewById(R.id.wbPostImage);
		final CheckBox cm3 = (CheckBox)view.findViewById(R.id.wbPostSource);
		final Spinner sp = (Spinner)view.findViewById(R.id.wbBoard);
		String st = s.getText();
		et1.setText("[zz]" + (st.length()>20?st.substring(0, 20)+"...":st));
		
		String title = "转载该微博";
		if (boardlist != null && boardlist.size() != 0) {
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			for (BoardObject b : boardlist) adapter.add("["+b.getName()+"]"+b.getCh());
			
			sp.setVisibility(View.VISIBLE);
			sp.setPrompt("从收藏里选择版面");
			sp.setAdapter(adapter);
			sp.setOnItemSelectedListener(new OnItemSelectedListener() {
				public void onItemSelected(AdapterView<?> view, View v, int position, long id) {
					board = boardlist.get(position);
				}

				public void onNothingSelected(AdapterView<?> view) {
				}
			});

			if (board == null) board = boardlist.get(0);
			else sp.setSelection(boardlist.indexOf(board));
		} else if (board != null) {
			title = "转载该微博至[" + board.getName() + "]";
		}
		
		
		new AlertDialog.Builder(this)
		.setTitle(title)
		.setView(view)
		.setCancelable(false)
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {					
			public void onClick(DialogInterface dialog, int which) {
				if (board != null)
					postDoc(s, et1.getText().toString(), cm1.isChecked(), cm2.isChecked(), cm3.isChecked(), board);
			}
		})
		.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		}).create().show();
	}
	
	private void postDoc(final Status status, final String title, final boolean postRetweet, final boolean postImage, final boolean postSource, final BoardObject bd) {
		UIUtil.runActionInThread(this, new UIUtil.ActionInThread<Status>() {
			@Override
			public void action() throws NetworkException, ContentException {
				DocObject newDoc = new DocObject(title, null, bd);
				try {
					StringBuffer content = new StringBuffer();
					if (postSource || (!postSource && !postRetweet)) {
						content.append((char)(27)+"[31m")
							.append(status.getUser().getScreenName())
							.append((char)(27)+"[m")
							.append(":").append(status.getText());
						if (status.getBmiddle_pic() != null && status.getBmiddle_pic().length() !=0 && postImage) {
							File f = UIUtil.cacheFromURL(status.getBmiddle_pic(), WeiboSinaActivity.this);
							if (f != null && f.exists()) {
								String p = ActionFactory.newInstance().newPostAction()
										.sendAttFile(f, bd.isAttach()?bd:HttpConfig.DEFAULT_UPLOAD_BOARD, GIFOpenHelper.readImageType(f));
								content.append("\n\n").append(p);
							}
						}
					}
					
					if (status.getRetweetDetails() != null && postRetweet) {
						content.append("\n\n")
							.append((char)(27)+"[31m")
							.append(status.getRetweetDetails().getRetweetingUser().getScreenName())
							.append((char)(27)+"[m")
							.append(":")
							.append((char)(27)+"[0;37m")
							.append(status.getRetweetDetails().getRetweetText())
							.append((char)(27)+"[m");
						if (status.getRetweetDetails().getBmiddle_pic() != null && status.getRetweetDetails().getBmiddle_pic().length() !=0 && postImage) {
							File f = UIUtil.cacheFromURL(status.getRetweetDetails().getBmiddle_pic(), WeiboSinaActivity.this);
							if (f != null && f.exists()) {
								String p = ActionFactory.newInstance().newPostAction()
										.sendAttFile(f, bd.isAttach()?bd:HttpConfig.DEFAULT_UPLOAD_BOARD, GIFOpenHelper.readImageType(f));
								content.append("\n\n").append(p);
							}
						}
					}
					
					newDoc.setContent(content.toString());
					ActionFactory.newInstance().newPostAction().sendPostDoc(newDoc, null, false, false, 0);
				} finally {
				}
			}
			@Override
			public void actionFinish() {
				Toast.makeText(WeiboSinaActivity.this, "转载成功", Toast.LENGTH_SHORT).show();
				//postSuccess();
			}
		});
	}
	
	private WeiboListScrollAction scrollAction = new WeiboListScrollAction();
	private class WeiboListScrollAction extends UIUtil.ActionInScroll {
		
		public WeiboListScrollAction() {
			new UIUtil().super();
		}
		
		@Override
		protected void actionClear() {
			list.clear();
		}

		@Override
		protected void actionScroll(int totalItemCount) {
			listWeibo(totalItemCount);
		}

		@Override
		protected void actionRemove(Object o) {
			list.remove(o);
		}
		
	}
	
	private class StatusListAdapter extends BaseAdapter {

		private List<Status> list;

		public StatusListAdapter(List<Status> list) {
			this.list = list;
		}

		public int getCount() {
			return list.size();
		}

		public Object getItem(int position) {
			return list.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View tv;
			if (convertView == null) {
				tv = LayoutInflater.from(WeiboSinaActivity.this).inflate(R.layout.weibosina_item, parent, false);
			} else {
				tv = convertView;
			}
			TextView text1 = (TextView)tv.findViewById(R.id.wbText);
			TextView text2 = (TextView)tv.findViewById(R.id.wbReText);
			TextView text3 = (TextView)tv.findViewById(R.id.wbTime);
			TextView text4 = (TextView)tv.findViewById(R.id.wbSource);
			LinearLayout re = (LinearLayout)tv.findViewById(R.id.wbRe);
			
			final ImageView icon = (ImageView)tv.findViewById(R.id.wbUserIcon);
			final ImageView i1 = (ImageView)tv.findViewById(R.id.wbImage);
			final ImageView i2 = (ImageView)tv.findViewById(R.id.wbReImage);
			
			Status s = list.get(position);
			text1.setText(renderText(s.getUser().getScreenName(), s.getText()));
			if (s.getRetweetDetails() != null) {
				RetweetDetails r = s.getRetweetDetails();
				re.setVisibility(View.VISIBLE);
				text2.setText(renderText("@" + r.getRetweetingUser().getScreenName(), s.getRetweetDetails().getRetweetText()));
			} else {
				re.setVisibility(View.GONE);
			}
						
			loadImage(s.getUser().getProfileImageURL().toString(), icon);
			loadImage(s.getBmiddle_pic(), i1);
			UIUtil.viewBigImage(s.getOriginal_pic(), i1, WeiboSinaActivity.this);
			if (s.getRetweetDetails() != null) {
				loadImage(s.getRetweetDetails().getBmiddle_pic(), i2);
				UIUtil.viewBigImage(s.getRetweetDetails().getOriginal_pic(), i2, WeiboSinaActivity.this);
			}
			
			text3.setText(formatCreateDate(s.getCreatedAt()));
			text4.setText(Html.fromHtml("来自:" + s.getSource()));
			
			text1.setMovementMethod(LinkMovementMethod.getInstance());
			text2.setMovementMethod(LinkMovementMethod.getInstance());
			
			if (position%2 == 1)
				tv.setBackgroundResource(R.drawable.weibo_selector1);
			else
				tv.setBackgroundResource(R.drawable.weibo_selector2);
			
			return tv;
		}		
	}
	
	private Spannable renderText(String user, String text) {
		SpannableStringBuilder ssb = new SpannableStringBuilder();
		ssb.append(user);
		ssb.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.sina_weibo_tag1)), 0, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		ssb.append(":");
		UIUtil.replacePattern(ssb, text, WEIBO_USER_PATTERN, new PatternListener() {
			public void onEnd(SpannableStringBuilder ssb) {
				return;
			}

			public void onPatternMatch(String source, SpannableStringBuilder ssb) {
				int s = ssb.length();
				ssb.append(source);
				ssb.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.sina_weibo_tag1)), s, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
			
		});
		
		UIUtil.makeSpanFromPattern(ssb, WEIBO_URL_PATTERN, new GroupListener() {
			public void onPatternMatch(String source, SpannableStringBuilder ssb, int start, int end) {
				ssb.setSpan(new URLSpan(source), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
		});
		return ssb;
	}
	
	private String formatCreateDate(Date createdAt) {
		Date now = new Date();
		long s = now.getTime() - createdAt.getTime();
		if (s > DateUtils.DAY_IN_MILLIS)
			return ((int)(s/DateUtils.DAY_IN_MILLIS)) + "天前";
		else if (s > DateUtils.HOUR_IN_MILLIS)
			return ((int)(s/DateUtils.HOUR_IN_MILLIS)) + "小时前";
		else if (s > DateUtils.MINUTE_IN_MILLIS)
			return ((int)(s/DateUtils.MINUTE_IN_MILLIS)) + "分钟前";
		else
			return ((int)(s/DateUtils.SECOND_IN_MILLIS)) + "秒前";
	}

	private void loadImage(final String src, final ImageView i) {
		if (src != null && src.length() != 0) {
			i.setVisibility(View.VISIBLE);
			i.setImageDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
			UIUtil.loadImageInThread(src, this, handler, i);
		} else {
			i.setVisibility(View.GONE);
		}
	}
}
